package net.jjjshop.front.controller.order;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.framework.common.api.ApiResult;
import net.jjjshop.framework.log.annotation.OperationLog;
import net.jjjshop.front.controller.BaseController;
import net.jjjshop.front.param.order.OrderBuyParam;
import net.jjjshop.front.vo.supplier.SupplierBuyVo;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Api(value = "pay", tags = {"订单支付管理"})
@RestController
@RequestMapping("/front/order/pay")
public class PayController extends BaseController {

    private final String appId = "1111";
    private final String mchId = "";
    private final String mchKey = "";
    private final String notifyUrl = "";

    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @OperationLog(name = "createOrder")
    @ApiOperation(value = "createOrder", response = String.class)
    public ApiResult<Map<String, Object>> createOrder(HttpServletRequest request, String orderNo, String subject){
        Map<String, Object> map = new HashMap<>();
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        BigDecimal totalFee = new BigDecimal(1);

        try {
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody("主题");
            orderRequest.setOutTradeNo("订单号");
            orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(String.valueOf(totalFee)));//元转成分
            orderRequest.setOpenid("openId");
            orderRequest.setSpbillCreateIp("userIp");
            orderRequest.setTimeStart("yyyyMMddHHmmss");
            orderRequest.setTimeExpire("yyyyMMddHHmmss");
            map.put("data",wxPayService.createOrder(orderRequest));
            return ApiResult.ok(map);
        } catch (Exception e) {
            log.error("微信支付失败！订单号：{},原因:{}", orderNo, e.getMessage());
            e.printStackTrace();
            map.put("msg","支付失败，请稍后重试！");
            return ApiResult.ok(map);
        }



    }

    /**
     异步回调接口代码内部会自动校验签名，您需要做的就是拿到结果之后直接根据业务逻辑进行处理就行了；
     需要处理下异常信息；
     回调返回接口可以直接使用WxPayNotifyResponse 返回处理成功，还是失败！
     */
    @ResponseBody
    @RequestMapping("/wx")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);

            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }

}
